package com.briup.pts.web.interceptor;

import com.briup.pts.config.auth.TokenMap;
import com.briup.pts.config.auth.UserDetails;
import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.mapper.AccountMapper;
import com.briup.pts.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 25095
 * @description 登录认证拦截器
 * @data 2024/11/26-09:12
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Value("${jwt.header}")
    private String header;
    @Resource
    private AccountMapper mapper;


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) {
        //如果请求方式为options，表示跨域的预请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        //获取token
        String token = request.getHeader(header);
        //对token进行校验
        String username = JwtUtil
                .fieldValue(token, "username", String.class);

        //从tokenmap中获取对应用户的token进行比较，如果不一致,从新登录
        String token2 = TokenMap.getToken(username);
        if (!token.equals(token2)){
            throw new ServiceException(ResultCode.TOKEN_IS_MISS);
        }


        //将当前登录用户分对象，放入到userDetail中
        Account account = mapper.findByUsername(username);
        UserDetails.setCurrentUser(account);

        //如果token校验没有问题返回true
        return true;
    }

    public void afterCompletion(HttpServletRequest request,HttpServletResponse response){
        UserDetails.clear();;
    }
}
